package com.leo.ibatis.demo.web.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.leo.ibatis.demo.criteria.ItemCriteria;
import com.leo.ibatis.demo.domain.Item;
import com.leo.ibatis.demo.service.ItemService;

public class ItemFormController extends SimpleFormController {

	private ItemService itemService;

	public void setItemService(ItemService itemService) {
		this.itemService = itemService;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected Map referenceData(HttpServletRequest request) throws Exception {
		String mode = ServletRequestUtils.getRequiredStringParameter(request, "mode");
		
		ItemCriteria itemCriteria = new ItemCriteria();
		ServletRequestDataBinder binder = createBinder(request, itemCriteria);
		binder.bind(request);
		
		Map map = new LinkedHashMap();
		map.put("mode",  mode);
		map.put("itemCriteria", itemCriteria);

		return map;
	}

	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
	}

	@Override
	protected void onBind(HttpServletRequest request, Object command, BindException errors) throws Exception {
	}

	@Override
	protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		Item item = null;
		
		String mode = ServletRequestUtils.getRequiredStringParameter(request, "mode");

		if (mode.equals("write")) {
			item = new Item();
		}
		
		if (mode.equals("edit")) {
			String itemid = ServletRequestUtils.getRequiredStringParameter(request, "itemid");

			item = itemService.select(itemid);
		}

		return item;
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
		String mode = ServletRequestUtils.getRequiredStringParameter(request, "mode");
		
		Item item = (Item) command;
		
		if (mode.equals("write")) {
			itemService.insert(item);
		} else if (mode.equals("edit")) {
			itemService.update(item);
		}

		return new ModelAndView(getSuccessView());
	}

}
